﻿//------------------------------
// Author: Yang Shulin
// Version: V1.0
// DateTime: 2011-3-20
//------------------------------

using System;
using System.Configuration;
using System.Reflection;

namespace Ysl.Data.SqlBuilder
{
    /// <summary>
    /// SqlBuilderFactory
    /// Sql语句服务工厂
    /// </summary>
    public static class SqlBuilderFactory
    {
        //初始SqlBuilder的命名空间
        private const string path = "Ysl.DbHelper.SqlBuilder";
        //获取ISqlBuilder具体类名的完整路径
        private static readonly string className;
        private static ISqlBuilder helper;
        private static Object locker;

        //静态构造函数
        static SqlBuilderFactory()
        {
            locker = new Object();

            string dbType = ConfigurationManager.AppSettings["DbType"];
            switch (dbType)
            {
                case "SqlServer":
                    className = path + ".MsSqlBuilder";
                    break;
                case "Oracle":
                    className = path + ".OracleSqlBuilder";
                    break;
                case "MySql":
                    className = path + ".MySqlBuilder";
                    break;
            }
        }

        /// <summary>
        /// 创建针对Sql Server的拼接Sql语句类
        /// </summary>
        /// <returns></returns>
        public static ISqlBuilder CreateSqlBuilder()
        {
            if (helper == null)
            {
                //lock 关键字可以用来确保代码块完成运行，而不会被其他线程中断
                lock (locker)
                {
                    helper = (ISqlBuilder)Assembly.Load(path).CreateInstance(className);
                }
            }

            return helper;
        }
    }
}
